package com.xdwanj.criminalintent.repository;

import static com.xdwanj.criminalintent.dao.CrimeDatabase.MIGRATION_1_2;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.room.Room;

import com.xdwanj.criminalintent.dao.CrimeDao;
import com.xdwanj.criminalintent.dao.CrimeDatabase;
import com.xdwanj.criminalintent.pojo.Crime;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CrimeRepository {

    private static final String DATABASE_NAME = "crime-database";

    private Context context;

    private final ExecutorService executor;

    private CrimeDao crimeDao;

    private CrimeDatabase database;

    private CrimeRepository(Context context) {
        this.context = context;

        database = Room
                .databaseBuilder(context, CrimeDatabase.class, DATABASE_NAME)
                .addMigrations(MIGRATION_1_2)
                .build();

        crimeDao = database.crimeDao();
        // 等同于executor = Executors.newSingleThreadExecutor();
        executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
    }

    public LiveData<List<Crime>> ListCrime() {
        return crimeDao.ListCrime();
    }

    public LiveData<Crime> getCrime(UUID id) {
        return crimeDao.getCrime(id);
    }

    public void updateCrime(Crime crime) {
        executor.execute(() -> crimeDao.updateCrime(crime));
    }

    public void addCrime(Crime crime) {
        executor.execute(() -> crimeDao.insertCrime(crime));
    }

//----------------------------------------------------------

    private static CrimeRepository INSTANCE = null;

    /**
     * 对CrimeRepository初始化
     *
     * @param context 上下文对象
     */
    public static void initialize(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new CrimeRepository(context);
        }
    }

    /**
     * 获取CrimeRepository单例
     *
     * @return CrimeRepository
     */
    public static CrimeRepository get() {
        if (INSTANCE != null) {
            return INSTANCE;
        }

        throw new IllegalStateException("CrimeRepository must be initialized");
    }
}
